<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>core-decorators.js</title>
</head>
<body>
    <h1>core-decorators.js</h1>
    <h2>第三方模块，提供了一些常用的装饰器</h2>

    <script>
        // @autobind
        function autobind(target, name, descriptor) {
            const method = descriptor.value;
            return {
                configurable: true,
                enumerable: false,
                get() {
                    return method.bind(this);
                }
            };
        }

        class Person {
            constructor(name) {
                this.name = name;
            }

            @autobind
            sayHello() {
                return `Hello, ${this.name}!`;
            }
        }

        // @readonly
        function readonly(target, name, descriptor) {
            descriptor.writable = false;
            return descriptor;
        }

        class Example {
            @readonly
            pi() { return 3.14; }
        }

        // @deprecate
        function deprecate(message = '该方法已废弃') {
            return function(target, name, descriptor) {
                const method = descriptor.value;
                descriptor.value = function(...args) {
                    console.warn(`警告: ${name} 已废弃. ${message}`);
                    return method.apply(this, args);
                };
                return descriptor;
            };
        }

        class API {
            @deprecate('请使用newMethod替代')
            oldMethod() {
                return 'old';
            }

            newMethod() {
                return 'new';
            }
        }

        // @debounce
        function debounce(wait) {
            return function(target, name, descriptor) {
                const method = descriptor.value;
                let timeout;

                descriptor.value = function(...args) {
                    clearTimeout(timeout);
                    timeout = setTimeout(() => {
                        method.apply(this, args);
                    }, wait);
                };

                return descriptor;
            };
        }

        class SearchInput {
            constructor() {
                this.value = '';
            }

            @debounce(300)
            search() {
                console.log(`搜索: ${this.value}`);
            }
        }

        // 使用示例
        const person = new Person('张三');
        const sayHello = person.sayHello;
        console.log(sayHello()); // "Hello, 张三!"

        const api = new API();
        api.oldMethod(); // 输出警告信息

        const searchInput = new SearchInput();
        searchInput.value = '测试';
        searchInput.search(); // 300ms后执行搜索
    </script>
</body>
</html> 